using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Data.SqlClient;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.DirectoryServices;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

namespace Stratman.Web.VSTS
{
    /// <summary>
    /// Page that allows the user to add a work item to a week so that they may allocate hours to it.
    /// </summary>
    public partial class AddToTimesheet : Page
    {
        /// <summary>
        /// Initializes the various TeamPlain objects responsible for rendering the header, enabling navigation,
        /// etc. and also instantiates the work item selector control if the request is not a post back.
        /// </summary>
        /// <param name="sender">
        /// Object from which this event originated.
        /// </param>
        /// <param name="e">
        /// Arguments associated with this event.
        /// </param>
        protected void Page_Load(object sender, EventArgs e)
        {
            // Get the WinNT directory object for the current user
            DirectoryEntry currentUser = new DirectoryEntry("WinNT://" + Request.LogonUserIdentity.Name.Replace("\\", "/"));

            DateTime startOfWeek = DateTime.ParseExact(Request.QueryString["ws"], "yyyy-MM-dd", null);
            startOfWeek = startOfWeek.AddDays(-1 * (int)startOfWeek.DayOfWeek);

            // Add an "Add" and a "Cancel" button to the standard menu header
            Menu[] menus = ToolbarCreator.GetToolbar(ToolbarItems.AddToWorkitem, ToolbarItems.Seperator, ToolbarItems.Cancel);
            menus[0].Items[0].Text = "&nbsp;Add Work Item";
            menus[0].Items[0].Value = "addtots";
            menus[0].Items[1].NavigateUrl = "timesheet.aspx?ws=" + startOfWeek.ToString("yyyy-MM-dd");
            menus[0].MenuItemClick += new MenuEventHandler(addtotimesheet_MenuItemClick);

            is1.Initialize();
            ph1.LoadHeaderDetails(fo1, new string[] { "<a href=\"index.aspx\">Home</a>", "<a href=\"timesheet.aspx?ws=" + Request.QueryString["ws"] + "\">Timesheet for " + currentUser.Properties["FullName"].Value + "</a>", "Add Work Item To Timesheet" }, 5, base.IsPostBack, menus);
            hh1.PageTitle = "Add Work Item To Timesheet";

            // Initialize the work item selector control if this is not a post back; this is a bit of a hack since
            // that control is not really generic and is only intended to setup relationships between work items.
            // However, it provides all of the necessary functionality to "find" a work item, no matter what the
            // context.  Since the control expects a work item object to be present in the session state bag, we
            // get the work item with an ID of 1:  we don't actually use it, but it allows the selector control to
            // initialize without throwing an exception
            if (!IsPostBack)
            {
                ViewState["SessionGuid"] = Guid.NewGuid().ToString();
                WorkItem item = AppVariables.TfsConnector.GetWorkitem(1);
                Session["CurrentWI" + ViewState["SessionGuid"].ToString()] = item;
                rwc.Initialize(ViewState["SessionGuid"].ToString());
            }
        }

        /// <summary>
        /// Handles the event that occurs when the user clicks the "Add" button to formally add a work item to a
        /// week in their timesheet.  We add an entry into the database so the work item will show up for the week
        /// but will not have any hours associated with it.
        /// </summary>
        /// <param name="sender">
        /// Object from which this event originated.
        /// </param>
        /// <param name="e">
        /// Arguments associated with this event.
        /// </param>
        protected void addtotimesheet_MenuItemClick(object sender, MenuEventArgs e)
        {
            // Get the ID of the work item that the user selected
            workitemquerylist workItems = (workitemquerylist)rwc.FindControl("Workitemquerylist1");
            int workItemId = workItems.GetCheckedWorkitemId();

            // Add an entry to the TimesheetEntries table with a hours value of 0 so that this work item will show
            // up for the week, but will have no hours associated with it
            SqlConnection databaseConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["TimesheetDatabase"].ConnectionString);
            SqlCommand command = new SqlCommand("usp_INS_WorkItemForWeek", databaseConnection);

            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add(new SqlParameter("@sid", Request.LogonUserIdentity.User.ToString()));
            command.Parameters.Add(new SqlParameter("@startOfWeek", Request.QueryString["ws"]));
            command.Parameters.Add(new SqlParameter("@workItemId", workItemId));

            databaseConnection.Open();
            command.ExecuteNonQuery();

            // Redirect the user to their timesheet for the week
            databaseConnection.Close();
            Response.Redirect("timesheet.aspx?ws=" + Request.QueryString["ws"]);
        }
    }
}
